package com.sinodata.bsm.cicp.finder.sco;

import java.io.BufferedReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.log4j.Logger;

import com.sinodata.bsm.cicp.util.CommandReader;

/**
 * 
 * <p>
 * Description: Sco系统的Memeory发现程序
 *  程序返回：内存页大小，内存大小
 *  
 *  其中：内存页大小取固定值 = 4096
 * </p>
 *
 * @author liulibo
 * @version 1.0

 * <p>
 * History: 
 *
 * Date                     Author         Version     Description
 * ---------------------------------------------------------------------------------
 * 2012-12-26 上午10:23:00          liulibo        1.0         To create
 * </p>
 *
 * @since 
 * @see
 */
public class ScoMem extends ScoFinder {

    private static final Logger logger = Logger.getLogger(ScoMem.class);
    private static String SHELL = "cat /usr/adm/messages | grep mem | sed -n  '1p' | awk  '{print $4}'";

    @Override
    public List<String[]> find(String ip, Map params) {
        List<String[]> list = new ArrayList<String[]>();
        BufferedReader reader = null;
        try {
            reader = CommandReader.getReader(ip, SHELL, 0, 0);
            String strLine = null;
            long mem = 0;
            if ((strLine = reader.readLine()) != null) {
                mem = getMem(strLine.trim());
            }
            String[] memRes = new String[5];
            list.add(memRes);
            memRes[0] = "0";
            memRes[1] = "Memory";
            memRes[2] = getHostName(ip) + " Memory";
            memRes[3] = "4096";
            memRes[4] = mem + ""; //内存大小,单位MB
            return list;
        } catch (Throwable e) {
            logger.error("failed to find sco memeory", e);
        }
        return null;
    }

    private long getMem(String strLine) {
        Pattern pattern = Pattern.compile("(\\d+).*");
        Matcher matcher = pattern.matcher(strLine);
        if (matcher.find()) {
            return new Long(matcher.group(1)) / 1024;
        }
        return 0;
    }
}
